import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {tableConfig, header} from '../data/config'
import store from 'store'
import {getUrlParam} from '../data/util'

const base = url.base

let table
let storeData

let param = {
  title: 'buildId',
  content: getUrlParam('house'),
  selectType: getUrlParam('selectType')
}

/*** 获取housetype方法 ***/
let houseType = {
  data: {
    hbuId: null,
    data: null,
    typeArr: [],
    activeEdit: null, //储存正在修改的户型数据
    houseTypeArr: [],
    pageNavFn: null,
    pageNavData: {  //储存分页数据
      pageSize: 10,
      currentPage: 1,
      pageData: []
    },
    allImgArr: null
  },
  init: () => {
    houseType.getData(param)
  },
  //重来新设计显示表格的方法
  getData: (res) => {
    let url = ''
    if (res.hbuId) {
      url = 'buildId=' + res.content + '&hbuId=' + res.hbuData
    } else {
      url = 'buildId=' + res.content
    }
    $.ajax({
      type: "GET",
      url: base + '/admin/houseType/facade.json?' + url,
      dataType: "json",
      headers: {
        myToken: Cookies.get('myToken')
      },
    }).then(res => {
      if (res.code == 0) {
        houseType.data.houseTypeArr = res
        //执行渲染方法
        houseType.setDataFn(houseType.data.houseTypeArr)
        houseType.data.allImgArr = res.object.elements
      }
    }).then(() => {
      houseType.bindEvent()
    })
  },
  //设置分页组件
  setPageNavFn: () => {
    // console.log('house type arr:', houseType.data.houseTypeArr)
    let data = {
      pageSize: houseType.data.pageNavData.pageSize,
      currentPage: houseType.data.pageNavData.currentPage,
      pageData: houseType.data.houseTypeArr.object.elements
    }
    let fn = new PageNav(data)
    houseType.data.pageNavFn = fn
    fn.initPageNav()
    houseType.renderPageNav()
  },
  //渲染分页按钮
  renderPageNav: () => {
    let len = houseType.data.pageNavFn.showData.length - 1
    // console.log('len:', len)
    let nodeList = ''
    for (let i = 0; i <= len; i++) {
      let node = `<li><a href="#" class="nav-page-number" nav-page-number="${i + 1}">${i + 1}</a></li>`
      nodeList += node
    }
    let str = `<nav aria-label="Page navigation">
      <ul class="pagination">
        <li>
          <a href="#" id="page-nav-previous" aria-label="Previous">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>
        ${nodeList}
        <li>
          <a href="#" id="page-nav-next" aria-label="Next">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      </ul>
    </nav>`
    $('#boot-page-nav').children().remove()
    $('#boot-page-nav').append(str)

    //页数按钮状态
    function navIndexActive() {
      // console.log('select:', document.querySelectorAll('.nav-page-number'))
      Array.prototype.forEach.call(document.querySelectorAll('.nav-page-number'), e => {
        // console.log('attr and page', $(e).attr('nav-page-number'), houseType.data.pageNavFn.currentPage)
        if ($(e).attr('nav-page-number') == houseType.data.pageNavFn.currentPage) {
          // console.log('it is', e)
          $(e).addClass('page-nav-active')
        } else {
          $(e).removeClass('page-nav-active')
        }
      })
    }

    navIndexActive()

    //给按钮绑定事件
    $('.nav-page-number').on('click', e => {
      let num = $(e.target).attr('nav-page-number')
      // console.log(num)
      //更改数据
      houseType.data.pageNavFn.choosePage(num)
      //删除之前渲染的数据
      houseType.unBindEvent()
      $('#myModal').remove()
      $('.edit-table-content').remove()
      //渲染数据
      houseType.setTypeArr(houseType.data.pageNavFn.activeData)
      houseType.bindEvent()
      navIndexActive()
    })

    //上一页按钮绑定事件
    $('#page-nav-previous').on('click', () => {
      let num = houseType.data.pageNavFn.currentPage - 1
      //更改数据
      houseType.data.pageNavFn.choosePage(num)
      //删除之前渲染的数据
      $('.edit-table-content').remove()
      //渲染数据
      houseType.setTypeArr(houseType.data.pageNavFn.activeData)
      navIndexActive()
    })

    //下一页按钮绑定事件
    $('#page-nav-next').on('click', () => {
      let num = houseType.data.pageNavFn.currentPage + 1
      //更改数据
      houseType.data.pageNavFn.choosePage(num)
      //删除之前渲染的数据
      $('.edit-table-content').remove()
      //渲染数据
      houseType.setTypeArr(houseType.data.pageNavFn.activeData)
      navIndexActive()
    })
  },
  //ajax获取数据后的渲染方法
  setDataFn: (res) => {
    // console.log('hello res', res)
    houseType.data.data = res
    houseType.data.hbuId = res.hbuId
    houseType.setHouseInfoHeader(res)
    houseType.setTableHeader()

    if (!param.selectType) {
      houseType.setPageNavFn()
      // houseType.setTypeArr(res.object.elements)
      houseType.setTypeArr(houseType.data.pageNavFn.activeData)
    } else {
      res.object.elements.forEach(k => {
        if (k.typeName == store.get('selectType').selectType) {
          houseType.setTypeArr([k])
        }
      })
    }
    houseType.setTypeSelect(res.houseType)
  },
  //渲染选中户型
  renderSelectedType: (res) => {
    // //删除之前的表格传入搜索数据重新渲染
    $('#table').children().remove()
    $('#myModal').remove()
    houseType.setTableHeader()
    res.object.elements.forEach(k => {
      if (k.typeName == res.selectType) {
        houseType.setTypeArr([k])
      }
    })
    houseType.unBindEvent()
    houseType.bindEvent()
  },
  //添加页面顶部房屋信息
  setHouseInfoHeader: (res) => {
    let str = `<div class="name">
                <i class="iconfont icon-loupanguanli"></i>
                <div class="title-body">
                <div class="title">楼盘名称：</div>
                <div class="title-container">${res.hsList.buildName}</div>
                </div>                
                </div>
                <div class="types">
                <i class="iconfont icon-huxingguanli"></i>
                <div class="title-body">
                <div class="title">户型数：</div>
                <div class="title-container">${res.hsList.hsTypeNum}</div>
                </div>                
                </div>
                <div class="house-num">
                <i class="iconfont icon-shouqianshujuguanli"></i>
                <div class="title-body">
                <div class="title">房源总数：</div>
                <div class="title-container">${res.hsList.hsBuildNum}</div>
                </div>
                </div>
                <div class="sold-num">
                <i class="iconfont icon-feiyongtongji"></i>
                <div class="title-body">
                <div class="title">已售套数：</div>
                <div class="title-container">
                ${res.hsList.hsSoldNum}</div>
                </div>
                </div>
                <div class="overage">
                <i class="iconfont icon-kaifashangfangkexinxi"></i>
                <div class="title-body">
                <div class="title">剩余套数：</div>
                <div class="title-container">
                ${res.hsList.hsBuildNum - res.hsList.hsSoldNum}</div>
                </div>
                </div>`
    $('#house-info').append(str)
  },
  //绑定事件
  houseTypeBind: () => {
    $('.change-btn .btn-border').on('click', () => {
      location.href = `./type.html?house=${param.content}`
    })
  },
  //设置户型表格
  setTableHeader: () => {
    $('#table').append(houseType.rendenTableHeader())
  },
  //渲染表头
  rendenTableHeader: () => {
    let str = `<tr class="header-gray"><th>户型名称</th><th>户型结构</th><th>户型房源数量</th>
               <th>建筑面积（㎡）</th><th>套内面积（㎡）</th><th>均价（元/㎡）</th>
               <th>朝向</th><th>项目类型</th><th>创建时间</th><th>操作</th></tr>`
    return str
  },
  //设置产品信息数据
  setTypeArr: (res) => {
    res.forEach(k => {
      houseType.data.typeArr.push({
        typeName: k.typeName,
        htStructure: k.htStructure,
        setInArea: k.setInArea,
        buildArea: k.buildArea,
        htAveragePrice: k.htAveragePrice,
        htOrientation: k.htOrientation,
        htItemType: k.htItemType,
        rawAddTime: k.rawAddTime,
        referencePrice: k.referencePrice,
        id: k.id,
        hPriceType: k.hPriceType,
        imgs: k.imgs
      })
    })
    res.forEach(k => {
      $('#table').append(houseType.renderTableBody(k))
    })
  },
  //渲染表身信息
  renderTableBody: (res) => {
    let date = new Date(res.rawAddTime)
    let thisDate = date.toLocaleDateString()
    let thisHour = date.toLocaleTimeString()
    let str = `<tr class="edit-table-content"><td>${res.typeName}户型</td>
               <td>${res.htStructure}</td>
               <td>${res.housesTotalCount}</td>
               <td>${res.buildArea}</td>
               <td>${res.setInArea}</td>
               <td>${res.htAveragePrice / 100}</td>
               <td>${res.htOrientation}</td>
               <td>${res.htItemType}</td>
               <td>${thisDate}${thisHour}</td>
               <td><button class="button" data-id="${res.id}">修改</button></td>
               </tr>`
    return str
  },
  //设置户型选择
  setTypeSelect: (res) => {
    let k = param.selectType
    res.forEach(k => {
      let str = `<option class="select-option" select-option="${k.typeName}">${k.typeName}</option>`
      $('#select-type').append(str)
    })
    $("#select-type").val(k)
  },
  //绑定事件
  bindEvent: () => {
    //房源管理按钮
    $('.change-btn .go-house').on('click', () => {
      location.href = `./house.html?house=${param.content}`
    })
    //户型管理按钮刷新页面
    $('.change-btn .go-house').next().on('click', () => {
      location.href = `./type.html?house=${param.content}`
    })
    //修改按钮和模态框
    $('#table .button').on('click', e => {
      houseType.data.typeArr.forEach(k => {
        if (k.id === $(e.target).attr('data-id')) {
          console.log('adas k:', k)
          houseType.data.activeEdit = k
          let imgUrl = ''
          houseType.data.allImgArr.forEach(j => {
            if (j.idStr == k.id) {
              console.log('j idStr', j.idStr, 'k id:', k.id, 'j id', j.id)
              imgUrl = j.imgs
              console.log('imgUrl:', imgUrl)
            }
          })

          //判断是否已有模态框
          if (document.querySelector('#myModal')) {
            // console.log('has modal')
            if (imgUrl) {
              $('#unit-img img').attr('src', (base + imgUrl))
              $('#unit-img img').attr('data-url', imgUrl)
            } else {
              $('#unit-img img').attr('src', '#')
              $('#unit-img img').attr('data-url', '#')
            }
            $('#edit-id').text(houseType.data.data.hsList.buildName)
            document.querySelector('#edit-typeName').value = k.typeName
            document.querySelector('#edit-htItemType').value = k.htItemType
            document.querySelector('#edit-htOrientation').value = k.htOrientation
            document.querySelector('#edit-buildArea').value = k.setInArea
            document.querySelector('#edit-setInArea').value = k.buildArea
            $('#edit-hPriceType').attr('edit-hPriceType', k.hPriceType)
            $('#edit-hPriceType').children().remove()
            let key = `<span class="span-title">价格类型:</span><button this-type="0" class="btn ${k.hPriceType !== 0 ? 'btn-default' : 'btn-primary'}" type="submit">建面</button>
                             <button this-type="1" class="btn ${k.hPriceType === 0 ? 'btn-default' : 'btn-primary'}" type="submit">套内</button>`
            $('#edit-hPriceType').append(key)
            document.querySelector('#edit-htAveragePrice').value = k.htAveragePrice / 100

            $('#myModal').modal('show')
          } else {
            // console.log('do not have')
            let str = `<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                     <div class="modal-dialog" role="document">
                       <div class="modal-content">
                         <div class="modal-header">
                           <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                           <h4 class="modal-title" id="myModalLabel">修改户型</h4>
                         </div>
                           <div class="modal-body">
                           <p><span class="span-title">楼盘:</span><span id="edit-id" edit-id="k.id">${houseType.data.data.hsList.buildName}</span></p>
                           <p><span class="span-title">户型名称:</span><input id="edit-typeName" type="text" value="${k.typeName}"></p>
                           <p><span class="span-title">户型项目类型:</span><input id="edit-htItemType" type="text" value="${k.htItemType}"></p>
                           <p><span class="span-title">户型朝向:</span><input id="edit-htOrientation" type="text" value="${k.htOrientation}"></p>
                           <p><span class="span-title">建筑面积:</span><input id="edit-buildArea" type="text" value="${k.buildArea}">㎡</p>
                           <p><span class="span-title">套内面积:</span><input id="edit-setInArea" type="text" value="${k.setInArea}">㎡</p>
                           <p id="edit-hPriceType" edit-hPriceType="${k.hPriceType}"><span class="span-title">价格类型:</span><button this-type="0" class="btn ${k.hPriceType !== 0 ? 'btn-default' : 'btn-primary'}" type="submit">建面</button>
                             <button this-type="1" class="btn ${k.hPriceType === 0 ? 'btn-default' : 'btn-primary'}" type="submit">套内</button>
                           </p>
                           <div id="special-p"><span class="span-title">户型图:</span>
                            <div id="special-span">
                              <form id="uploadForm" enctype="multipart/form-data">
                                  <input type="file" id="htoImge" name="htoImge">
                                   <input type="button" id="update-img" data-id="" value="上传户型图" class="btn btn-primary">
                              </form>                           
                            </div>  
                           </div>
                           <p><span class="span-title">户型图:</span><span id="unit-img"><img data-url="${imgUrl}" src="${base + imgUrl}" alt=""></span></p>
                           <p><span class="span-title">均价:</span><input id="edit-htAveragePrice" type="text" value="${k.htAveragePrice / 100}">元/㎡</p>
                           <button id="edit-submit" type="button" class="btn btn-primary">提交</button>
                          </div>
                       </div>
                      </div>
                     </div>`
            $('.content-wrap').append(str)
            $('#myModal').modal('show')
          }
          //价格类型按钮更改事件
          $('#edit-hPriceType button').on('click', e => {
            $(e.target).addClass('btn-primary')
            $(e.target).siblings().removeClass('btn-primary').addClass('btn-default')
            $(e.target).parent().attr('edit-hPriceType', $(e.target).attr('this-type'))
          })

          $('#uploadForm').on('submit', e => {
            e.preventDefault()
            let formData = new FormData();
            let id = $('#edit-id').attr('edit-id')
            formData.append('htoImge', $('#htoImge')[0].files[0])
            formData.append('htId', id)

            $.ajax({
              url: base + '/admin/houseType/imageUploader',
              type: 'POST',
              cache: false,
              data: formData,
              processData: false,
              contentType: false,
              headers: {
                myToken: Cookies.get('myToken')
              }
            }).done(function (res) {
              if (res.code === 0) {
                let str = res.object
                $('#update-img').attr('data-id', str)
                // alert('上传成功')
                $('#unit-img img').attr('src', (base + str))
                $('#unit-img img').attr('data-url', str)
              }
            }).fail(function (res) {
            });

          })

          $('#update-img').on('click', () => {
            $('#uploadForm').submit()
          })

          //绑定按钮提交事件
          $('#edit-submit').on('click', () => {
            let res = houseType.data.activeEdit
            let data = {
              id: res.id,
              typeName: $('#edit-typeName')[0].value,
              htItemType: $('#edit-htItemType')[0].value,
              htOrientation: $('#edit-htOrientation')[0].value,
              buildArea: $('#edit-buildArea')[0].value,
              setInArea: $('#edit-setInArea')[0].value,
              htAveragePrice: $('#edit-htAveragePrice')[0].value,
              hPriceType: $('#edit-hPriceType').attr('edit-hPriceType'),
              imgs: $('#unit-img img').attr('data-url')
            }
            console.log('imgs:', data.imgs)
            $.ajax({
              type: "POST",
              url: base + '/admin/houseType/edit.json?',
              data: data,
              dataType: "json",
              headers: {
                myToken: Cookies.get('myToken')
              },
            }).then(() => {
              $('#myModal').modal('hide')
              location.reload()
            })
          })
        }
      })
      $(e.target)
    })
    //绑定选中事件
    $('#search-btn').on('click', () => {
      let str = $('#select-type').find("option:selected").attr('select-option')
      console.log(str)
      if (str) {
        let data = houseType.data.data
        data.selectType = str
        store.set('selectType', data)
        let url = `./type.html?house=${param.content}&selectType=${data.selectType}`
        window.location.href = url
      } else {
        let url = `./type.html?house=${param.content}`
        window.location.href = url
      }
    })
  },
  //移除绑定事件
  unBindEvent: () => {
    $('.change-btn .go-house').unbind()
    $('#table .button').unbind()
    $('#select-search').unbind()
  }
}
/*** 获取housetype方法结束 ***/

/*** 启动页面 ***/
houseType.init()

/*** 分页组件 ***/
function PageNav(data) {
  this.pageSize = data.pageSize
  this.currentPage = data.currentPage
  this.pageData = data.pageData
  this.showData = []
  this.activeData = []
  //初始化分页组件
  this.initPageNav = () => {
    //按照pageSize currentPage更改数组整理数组
    let pages = Math.floor(this.pageData.length / this.pageSize) + 1
    let arr = this.pageData.slice()
    this.showData = []
    for (let i = 0; i < pages; i++) {
      if (arr.slice(i * this.pageSize, i * this.pageSize + this.pageSize).length > 0) {
        this.showData.push(arr.slice(i * this.pageSize, i * this.pageSize + this.pageSize))
      }
    }
    this.activeData = this.showData[this.currentPage - 1]
  }
  //显示指定页面
  this.choosePage = (res) => {
    this.currentPage = res
    if (this.currentPage <= this.showData.length && this.currentPage > 0) {
      this.activeData = this.showData[this.currentPage - 1]
    } else {
    }
  }
  //更改pageSize
  this.changePageSize = (res) => {
    if (res > 0) {
      this.pageSize = Math.floor(res)
      //更改后重新加载
      this.initPageNav()
    }
  }
}

// // 点击列表的时候传递数据到全局变量
// table.on('click-row.bs.table', (e, data, el) => {
//   storeData = data
// })